//
//  FindDetailViewController.m
//  Find
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 Reiko. All rights reserved.
//

#import "LostDetailViewController.h"


@interface LostDetailViewController ()

@property (nonatomic, retain)NSMutableArray *commentDataArray;
@property (nonatomic, strong)NSString *clientId;
@property (nonatomic, retain)NSURL *imageUrl;

@end

@implementation LostDetailViewController


- (void)viewWillAppear:(BOOL)animated{

   
        [self setUpLostHeaderData];
        [self setUpLostCommentsData];
        [self addToolBar];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.BoomToolBar removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent=NO;
//    self.navigationController.hidesBottomBarWhenPushed = YES;
    [self addSubviews];
    
//    [self monitorKeyboard];
}
#pragma mark === 监听键盘
//- (void)monitorKeyboard{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//}
//
//
//- (void)keyboardWillShow:(NSNotification *)notification{
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *keyboardValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
//    CGRect keyboardRect = [keyboardValue CGRectValue];
//    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
//    NSTimeInterval animationDutation;
//    [animationDurationValue getValue:&animationDutation];
//    [self autoMoveKeyBoard:keyboardRect time:animationDutation];
//}
//- (void)keyboardWillHide:(NSNotification *)notification{
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *keyboardValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
//    CGRect keyboardRect = [keyboardValue CGRectValue];
//    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
//    NSTimeInterval animationDuration;
//    [animationDurationValue getValue:&animationDuration];
//    [self autoMoveKeyBoard:keyboardRect time:animationDuration];
//}
//- (void)autoMoveKeyBoard:(CGRect)rect time:(NSTimeInterval)time{
//    [UIView animateWithDuration:time animations:^{
//        self.commentBgView.frame = CGRectMake(0, kScreenHeight-kTabBarHeight-kNavBarHeight-rect.size.height-_commentBgViewHeight, kScreenWidth, 200);
//    }];
//}


- (void)setUpLostHeaderData
{
   
   // LostMessageModel *lostModel = [LostMessageModel objectWithoutDataWithObjectId:self.objectID];
LostMessageModel *lostModel =  (LostMessageModel *)[AVQuery getObjectOfClass:@"LostMessageModel" objectId:self.objectID error:nil];
    AVUser *user1 = lostModel.user;
    AVUser *user2 = [AVQuery getUserObjectWithId:user1.objectId];
    self.clientId = user2.username;
    // 用户名
    self.headerView.userNameLabel.text  =  user2.username;
    // 头像
    NSString *urlString = [[user2 valueForKey:@"photoImage"] getThumbnailURLWithScaleToFit:NO width:100 height:100];
    self.imageUrl = [NSURL URLWithString:urlString];
    [self.headerView.mineImageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
    //  标题
    self.headerView.titleLabel.text = lostModel.title;
    // 距离
    AVUser *user = [AVUser currentUser];
    CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:[[user valueForKey:@"latitude"] floatValue] longitude:[[user valueForKey:@"longitude"] floatValue]];
    CLLocation *publishLocation = [[CLLocation alloc] initWithLatitude:[lostModel.latitude floatValue] longitude:[lostModel.longitude floatValue]];
    CLLocationDistance distance = [userLocation distanceFromLocation:publishLocation];
    if (lostModel.latitude == NULL && lostModel.longitude == NULL) {
        self.headerView.distanceLabel.text = @"未定位";
    } else {
      if (distance < 1000){
        self.headerView.distanceLabel.text = [NSString stringWithFormat:@"%dm",(int)distance];
      } else {
        self.headerView.distanceLabel.text = [NSString stringWithFormat:@"%.1fkm",(distance / 1000)];
      }
    }
    // 内容
    self.headerView.detailLabel.text = lostModel.context;
    // 上传的日期
    NSDateFormatter *dateFoematter = [[NSDateFormatter alloc] init];
    [dateFoematter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    NSRange range = NSMakeRange(6, 11);
    self.headerView.timeLabel.text = [[dateFoematter stringFromDate: lostModel.createdAt] substringWithRange:range];
    // 位置
    self.headerView.addressLabel.text = lostModel.location;
    self.headerView.collectCountLabel.text = [NSString stringWithFormat:@"(%@)",lostModel.collectCount];
    // 图片

    [self messagePhotoWithimageArray:lostModel.imageArray];
    // 图片数量
    self.photoCount = (int)lostModel.imageArray.count;
    
    
    }

- (void)setUpLostCommentsData
{
     LostMessageModel *lostModel =  (LostMessageModel *)[AVQuery getObjectOfClass:@"LostMessageModel" objectId:self.objectID error:nil];
    AVRelation *relation = [lostModel relationforKey:kComment];
    [[relation query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.commentDataArray = [NSMutableArray arrayWithArray:objects];
        } else {
          
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    }];

}
#pragma mark -- 用户传上来的图片
- (void)messagePhotoWithimageArray:(NSArray *)imageArray{
    for (int i = 0; i < imageArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth*0.03 + kScreenWidth*0.485*i, 0, kScreenWidth*0.455, kScreenHeight*0.25)];
        imageView.layer.cornerRadius = 5;
        imageView.userInteractionEnabled = YES;
        imageView.layer.masksToBounds = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
        [self.scrollView addSubview:imageView];
        
        UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth*i, 0, kScreenWidth, kScreenWidth)];
        bgImageView.userInteractionEnabled = YES;
        bgImageView.tag = 100+i;
        [bgImageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
        [self.bgScrollView addSubview:bgImageView];
    }
    self.scrollView.contentSize = CGSizeMake(0.485*imageArray.count*kScreenWidth + kScreenWidth*0.03, 10);
    self.bgScrollView.contentSize = CGSizeMake(imageArray.count*kScreenWidth, 10);
}
#pragma mark -- 手势代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

#pragma mark -- 点击图片
- (void)clickPhotoView:(UITapGestureRecognizer *)tap{
    self.animation = @"photo";
    CGPoint point = [tap locationInView:self.scrollView];
    NSNumber *number = [NSNumber numberWithFloat:point.x / (kScreenWidth*0.485)];
    int i = [number intValue];
    self.bgScrollView.contentOffset = CGPointMake(kScreenWidth*i, 0);
    self.commentButton.userInteractionEnabled = NO;
    self.privateLetterButton.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.bgScrollView.frame  = CGRectMake(0, (kScreenHeight- kTabBarHeight- kNavBarHeight -kScreenWidth)/2, kScreenWidth, kScreenWidth);
        self.visualView.alpha = 0.8;
    }];
}


#pragma mark 地下的toolBar
- (void)addToolBar
{
    self.BoomToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, kScreenHeight - kTabBarHeight, kScreenWidth, kTabBarHeight)];
    [self.BoomToolBar setBarTintColor:kFindListCellLabelTextColor];
    UIWindow *window = [[[UIApplication sharedApplication]delegate]window];
    [window addSubview:self.BoomToolBar];
    
    self.commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.commentButton.frame = CGRectMake(0, 0, kScreenWidth / 2, kTabBarHeight);
    [self.commentButton setTitle:@"评论" forState:UIControlStateNormal];
    [self.commentButton setImage:[UIImage imageNamed:@"pinlun2"] forState:UIControlStateNormal];
    [self.commentButton setImage:[UIImage imageNamed:@"pinlun2"] forState:UIControlStateHighlighted];
    [self.commentButton addTarget:self action:@selector(actionCommentButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.BoomToolBar addSubview:self.commentButton];
    
    self.privateLetterButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.privateLetterButton.frame = CGRectMake(kScreenWidth / 2, 0, kScreenWidth / 2, kTabBarHeight);
    [self.privateLetterButton setTitle:@"私信" forState:UIControlStateNormal];
    [self.privateLetterButton setImage:[UIImage imageNamed:@"sixin2"] forState:UIControlStateNormal];
    [self.privateLetterButton setImage:[UIImage imageNamed:@"sixin2"] forState:UIControlStateHighlighted];
    [self.privateLetterButton addTarget:self action:@selector(actionPrivateLetterButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.BoomToolBar addSubview:self.privateLetterButton];
}
#pragma mark -- 布局视图
- (void)addSubviews{
    
#pragma mark -- 左上角返回按钮
    //    lostBackButton.image = [UIImage imageNamed:@"lostDetailBack"];
    UIBarButtonItem * leftBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Returns"] style:(UIBarButtonItemStyleDone) target:self action:@selector(findDetailLeftBarButton)];
    leftBarButton.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    //
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight -kNavBarHeight-kTabBarHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    self.headerView = [[DetailView alloc] init];
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, self.headerView.commentButton.frame.origin.y + self.headerView.commentButton.frame.size.height + 10);
    self.tableView.tableHeaderView = self.headerView;
//    [self givePhotoAddGestureRecognizer]; // 添加手势
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight*0.3)];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.headerView.photoBgView addSubview:self.scrollView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickPhotoView:)];
    tap.delegate = self;
    [self.scrollView addGestureRecognizer:tap];
    
    self.visualView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    self.visualView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavBarHeight-kTabBarHeight);
    self.visualView.alpha = 0;
    [self.view addSubview:self.visualView];

    
    self.bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(kScreenWidth/2, kScreenHeight/2, 0, 0)];
    //self.bgScrollView.backgroundColor = [UIColor redColor];
    self.bgScrollView.showsHorizontalScrollIndicator = NO;
    self.bgScrollView.showsVerticalScrollIndicator = NO;
    self.bgScrollView.pagingEnabled = YES;
    self.bgScrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.bgScrollView];
 
    // 收藏按钮添加点击事件
    [self.headerView.collectButton addTarget:self action:@selector(actionCollectButton:) forControlEvents:(UIControlEventTouchUpInside)];
  //  [self.headerView.transpondButton addTarget:self action:@selector(actionTranspondButton:) forControlEvents:UIControlEventTouchUpInside];
  //  [self.headerView.moreButton addTarget:self action:@selector(actionMoreButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self setCommentView];
}

#pragma mark -- 左上角返回按钮
- (void)findDetailLeftBarButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- 评论View
- (void)setCommentView{
    
    self.commentBgView = [[UIView alloc] initWithFrame:CGRectMake(0, (kScreenHeight-280)*0.8+kScreenHeight, kScreenWidth, (kScreenHeight-280)*0.7)];
    self.commentBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.commentBgView];
    
    self.commentContextView = [[UITextView alloc] initWithFrame:CGRectMake((kScreenHeight-280)*0.05, 10, kScreenWidth-40, (kScreenHeight-280)*0.48)];
    self.commentContextView.font = [UIFont systemFontOfSize:16];
    self.commentContextView.backgroundColor = kFindListCellLabelTextColor;
    [self.commentBgView addSubview:self.commentContextView];
    
    //
    self.sendCommentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendCommentButton.frame = CGRectMake(kScreenWidth-70, CGRectGetMaxY(self.commentContextView.frame)+(kScreenHeight-280)*0.03, 60, (kScreenHeight-280)*0.12);
    self.sendCommentButton.backgroundColor = kFindListCellLabelTextColor;
    self.sendCommentButton.layer.cornerRadius = 5;
    [self.sendCommentButton setTitle:@"评论" forState:UIControlStateNormal];
    [self.sendCommentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sendCommentButton addTarget:self action:@selector(actionSendCommentButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.commentBgView addSubview:self.sendCommentButton];
    
}
#pragma mark == 发送评论
- (void)actionSendCommentButton:(UIButton *)sender{
    [self performSelector:@selector(touchesBegan:withEvent:) withObject:nil];
    if ([self.commentContextView.text isEqualToString:@""]) {
        [self showAlterViewWithTitle:@"提示" Message:@"请输入评论内容"];
    } else {
        AVUser *user = [AVUser currentUser];
        if (user) {
            CommentModel *commentModel = [[CommentModel alloc] init];
            commentModel.user = user;
            
            commentModel.context = self.commentContextView.text;
            [commentModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (error) {
            
                } else {
                 LostMessageModel *lostModel = [LostMessageModel objectWithoutDataWithObjectId:self.objectID];
                  AVRelation *collectLost = [lostModel relationforKey:kComment];
                      [collectLost addObject:commentModel];
                    [lostModel saveInBackground];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self setUpLostCommentsData];
                        [self.tableView reloadData];
                        
                    });
                }
                 [self showAlterViewWithTitle:@"提示" Message:@"评论成功"];
            }];
        } else {
          [self showAlterViewWithTitle:@"提示" Message:@"请先登录"];
        }

    }
}
// 取出所有的评论





#pragma mark -- 收藏按钮添加点击事件
- (void)actionCollectButton:(UIButton *)sender
{
  
    AVUser *user = [AVUser currentUser];
        if (user) {
            LostMessageModel *lostModel =  (LostMessageModel *)[AVQuery getObjectOfClass:@"LostMessageModel" objectId:self.objectID error:nil];
             AVRelation *collectLost = [user relationforKey:@"collectLost"];
            NSArray *array = [[collectLost query] findObjects];
            for (LostMessageModel *model in array) {
                if ([model.objectId isEqualToString:lostModel.objectId]) {
                    [self showAlterViewWithTitle:@"提示" Message:@"已收藏过了"];
                    return;
                }
            }
            // 保存的时候同时获取新值
            lostModel.fetchWhenSave = YES;
            [lostModel incrementKey:@"collectCount" byAmount:@1];
            [lostModel saveInBackground];
            [collectLost addObject:lostModel];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                [self showAlterViewWithTitle:@"提示" Message:@"收藏成功"];
                    self.headerView.collectCountLabel.text = [NSString stringWithFormat:@"(%@)",lostModel.collectCount];
                    
                    
                } else {
                  
                }
            }];
            
        } else {
            LoginViewController  *loginVC = [[LoginViewController alloc] init];
            UINavigationController *naC = [[UINavigationController alloc] initWithRootViewController:loginVC];
            [self presentViewController:naC animated:YES completion:nil];
}
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.commentContextView resignFirstResponder];
    if ([self.animation isEqualToString:@"photo"]) {
        self.commentButton.userInteractionEnabled = YES;
        self.privateLetterButton.userInteractionEnabled = YES;
        
        [UIView animateWithDuration:0.5 animations:^{
            self.bgScrollView.frame = CGRectMake(kScreenWidth/2, kScreenHeight/2, 0, 0);
            self.visualView.alpha = 0;
        }];
        
        
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            self.commentBgView.frame = CGRectMake(0, -(kScreenHeight-280)*0.8, kScreenWidth, (kScreenHeight-280)*0.7);
            self.visualView.alpha = 0;
        } completion:^(BOOL finished) {
            self.commentBgView.frame = CGRectMake(0, (kScreenHeight-280)*0.8+kScreenHeight, kScreenWidth, (kScreenHeight-280)*0.7);
        }];
    }
}



#pragma mark -- tableView的代理方法
// 多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.commentDataArray.count;
    
    
}
// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"LostDetailCell";
    FindDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[FindDetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
#pragma mark  =-- 适应label的高度 跟 label下面控件的位置
    AVObject *object = self.commentDataArray[indexPath.row];
    
    
    AVUser *user1 = [object valueForKey:@"user"];
    //    AVUser *user2 = [AVQuery getUserObjectWithId:user1.objectId];  // 同步请求数据导致界面卡顿
    AVQuery * query = [AVQuery queryWithClassName:@"_User"];
    [query  getObjectInBackgroundWithId:user1.objectId block:^(AVObject *object, NSError *error) {
        NSString *urlString = [[object valueForKey:@"photoImage"] getThumbnailURLWithScaleToFit:NO width:100 height:100];
            [cell.mineImageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
    }];
    
    NSDateFormatter *dateFoematter = [[NSDateFormatter alloc] init];
    [dateFoematter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    NSRange range = NSMakeRange(6, 11);
    cell.timeLabel.text = [[dateFoematter stringFromDate: object.createdAt] substringWithRange:range];
    NSString *tempStr = [object valueForKey:@"context"];
    CGFloat newheight = [self changeLabelHeightWithText:tempStr width:kScreenWidth*0.86-30 font:kDetailButtonFont];
    CGRect detailLabelFrame = cell.detailLabel.frame;
    detailLabelFrame.size.height = newheight;
    cell.detailLabel.frame = detailLabelFrame;
    
    cell.detailLabel.text = tempStr;

    UIView *selectedView = [[UIView alloc] init];
    selectedView.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = selectedView;
    

    return cell;
}
// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *tempStr = [self.commentDataArray[indexPath.row] valueForKey:@"context"];
    CGFloat newheight = [self changeLabelHeightWithText:tempStr width:kScreenWidth*0.86-30 font:kDetailButtonFont];
    
    return 78+newheight;
    
}

#pragma mark -- 私信 评论点击方法
- (void)actionPrivateLetterButton:(UIButton *)sender{
    // 创建一个 AVIMClient 实例
  
    AVUser *user = [AVUser currentUser];
    if (user){
      AVIMClient *imClient = [AVIMClient defaultClient];
    [imClient openWithClientId:user.username callback:^(BOOL succeeded, NSError *error){
        if (error) {
           
        } else {

            [self action];
        }
    }];
    } else {
        [self showAlterViewWithTitle:@"提示" Message:@"请先登录"];
    }
}


- (void)actionCommentButton:(UIButton *)sender{
    self.animation = @"comment";
    [UIView animateWithDuration:0.5 animations:^{
        self.commentBgView.frame = CGRectMake(0, (kScreenHeight-280)*0.2, kScreenWidth, (kScreenHeight-280)*0.7);
        self.visualView.alpha = 0.8;
    }];
}

- (void)action
{
    
    // 获取 AVIMConversationQuery 实例
    AVIMConversationQuery *query = [[AVIMClient defaultClient] conversationQuery];
    
    /* 构建查询条件
     * 注意：比较建议开发者仔细阅读以下三行代码，这三个条件同时进行查询在数据量日益增加的时候，也能保持查询的性能不受太大影响。
     */
    [query whereKey:@"m" containsAllObjectsInArray:@[[AVIMClient defaultClient].self.clientId, self.clientId]];
    [query whereKey:@"m" sizeEqualTo:2];
    [query whereKey:AVIMAttr(@"customConversationType")  equalTo:@(1)];
    query.cachePolicy = kAVCachePolicyNetworkOnly;
    [AVOSCloud setAllLogsEnabled:YES];
    
    // 执行查询
    [query findConversationsWithCallback:^(NSArray *objects, NSError *error) {
        if(objects.count == 0){
            NSDictionary *attributes = @{ @"customConversationType": @(1) };
            [[AVIMClient defaultClient] createConversationWithName:@"" clientIds:@[self.clientId] attributes:attributes options:AVIMConversationOptionNone callback:^(AVIMConversation *conversation, NSError *error) {
                FindPrivateLetterVC *privateLetterVC = [[FindPrivateLetterVC alloc] init];
                privateLetterVC.imageUrl = self.imageUrl;
                
                [privateLetterVC setTargetClientId:self.clientId];
                // 设置私聊所在的具体对话
                [privateLetterVC setCurrentConversation:conversation];
                [self.navigationController pushViewController:privateLetterVC animated:YES];
              
            }];
        }
        else{
            FindPrivateLetterVC *privateLetterVC = [[FindPrivateLetterVC alloc] init];
            privateLetterVC.imageUrl = self.imageUrl;
            [privateLetterVC setTargetClientId:self.clientId];
            // 设置私聊所在的具体对话
            [privateLetterVC setCurrentConversation:[objects objectAtIndex:0]];
           
            [self.navigationController pushViewController:privateLetterVC animated:YES];
            // [self performSegueWithIdentifier:@"toSingleChat" sender:[objects objectAtIndex:0]];
        }
    }];
    

}



#pragma mark -- 自适应label的高度
- (CGFloat)changeLabelHeightWithText:(NSString *)text width:(CGFloat)width font:(CGFloat)font{
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font] forKey:NSFontAttributeName];
    CGRect newFrame = [text boundingRectWithSize:CGSizeMake(width, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return newFrame.size.height;
}


- (void)showAlterViewWithTitle:(NSString *)title Message:(NSString *)message
{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [self performSelector:@selector(closeAlter:) withObject:alertView afterDelay:1];
    [self presentViewController:alertView animated:YES completion:nil];
}

// 设置1秒之后消失
- (void)closeAlter:(UIAlertController *)alert
{
    [alert dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
